package com.wander.rep.db4o;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

import android.content.Context;
import android.util.Log;

public final class SingletonHelper {


	private static SingletonHelper instance;

	private final static String TAG = "SingletonHelper";

	private static Context context;

	private static ObjectContainer database; 
	private static final String DATABASE_NAME = "android.db4o";
	private static final int DATABASE_MODE = 0;

	/*
	 * SingleTon Helper class for Db40
	 */
	private SingletonHelper(Context context){

		this.context = context;

	}

	/*
	 * Returns instance of DB object
	 */
	public static synchronized SingletonHelper getInstance(Context context){
		if(instance == null)
		{
			instance = new SingletonHelper(context);
			openDb();
		}
		return instance;
	}

	/*
	 * Opens Database
	 */
	private static void openDb()
	{
		try {
			if (database == null) {
				database = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),
						db4oDBFullPath());
			}
		} catch (Exception ie) {
			Log.e(TAG, ie.toString());
		}


	}

	/*
	 * Returns full path of DB Location
	 */
	public static String db4oDBFullPath() {
		return context.getDir("data", DATABASE_MODE) + "/" + DATABASE_NAME;
	}

	/*
	 * Closes Database
	 */
	public void close() {
		if (this.database != null) {
			this.database.close();
		}
	}

	/*
	 * Returns Database Session
	 */
	public ObjectContainer getDatabaseSession() {
		openDb();
		return database.ext().openSession();
	}
}